package com.airpi.heavy_tasks;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;


/**
 * Class which allows to interact with the server. Once you've instanciate an object of this class, you can use the "connect" method
 * which will send the string entered as argument to the server.
 * @author : Antoine Vaillant
 */

public class Connexion{
	InetAddress serverAddr = null; //IP address of the server
	Socket socket = null; //Socket used to communicate with the server
	private static int SERVERPORT = 8082; //Port of the server
	boolean answerReceived = false;
	String input;


	/**
	 * The instantiation of a Connexion object creates a socket on the designated IP address and ServerPort
	 * @param ip : IP address of the server
	 * @param port : Port of the server
	 */

	public Connexion(String ip){
		try {
			this.serverAddr = InetAddress.getByName(ip);
			this.socket = new Socket(serverAddr, SERVERPORT);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Method receiving the answer of the server after the send of a command
	 * @throws : IOException
	 */

	public String answerFromServer(){
		BufferedReader in;
		String tmp;
		this.input="";
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while((tmp = in.readLine()) != null){
				this.input += tmp;
			}
			if(this.input.length()>1){
				return this.input;
			}else{
				return null;
			}
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * Method sending the String corresponding to the command desired to the server
	 * @param : command sent to the server
	 * @throws: UnknownHostException
	 * @throws : IOException
	 */
	public void sendToServer(String command){
		try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			out.println(command);
		}
		catch (UnknownHostException e) {
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}

	}

	public void closeSocket() throws IOException{
		try{
			this.socket.close();
		}catch (IOException e){
			e.printStackTrace();
		}
	}

	public Socket getSocket() {
		return socket;
	}
	
}
